import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { fetchPost, deletePost } from '../actions/index';
import { Link } from 'react-router';

class PostsShow extends Component {
  static contextTypes = {
    router: PropTypes.object
  };

  constructor(props) {
    super(props);
    this.state = {
      loading: true
    }
  }

  componentWillMount() {
    this.props.fetchPost(this.props.params.id).then((res) => {
      this.setState({
        loading: false
      });
    })
  }

  deletePost() {
    this.setState({
      loading: true
    });
    this.props.deletePost(this.props.params.id).then(err => {
      console.log(err);
        this.setState({
          loading: false
        });
      this.context.router.push('/');
    })
  }

  render() {
    console.log(this.props.post);
    if(!this.props.post) {
      return (
        <article>
          正在加载中...
        </article>
      )
    }
    return (
      <div>
        <Link to="/">Back to list</Link>
        <button className="btn btn-danger pull-xs-right" onClick={ this.deletePost.bind(this) }>
          { this.state.loading ? '正在删除...' : '删除'}
        </button>
        <article>
          <h1>{ this.props.post.title }</h1>
          <section>
            <p>Categories: { this.props.post.categories }</p>
            <div dangerouslySetInnerHTML={{__html: this.props.post.content}}></div>
          </section>
        </article>

      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    post: state.posts.post
  }
}

export default connect(mapStateToProps, { fetchPost, deletePost })(PostsShow);
